﻿using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.PixelFormats;

namespace TextureGenerator.Mechanics
{
    public class InputProcessor
    {
        public static int[,] Run(string path,float blurSigma,int size)
        {
            var img = (Image<Rgb24>)Image.Load(path);

            int w = img.Width;
            int h = img.Height;
            int s = Math.Min(w, h);
            int marginX = 0, marginY = 0;
            if (w > h)
                marginX = (w - h) / 2;
            else
                marginY = (h - w) / 2;
            Rectangle rect = new(marginX, marginY, s, s);
            img.Mutate(x => x.Crop(rect).Resize(new Size(size,size)).GaussianBlur(blurSigma*size/256));

            int[,] depth = new int[size, size];
            float min = 255;
            float max = 0;
            for(int i = 0; i < size; i++)
            {
                for(int j = 0; j < size; j++)
                {
                    var c = img[i, j];
                    int value = 255 - Math.Min(c.R, Math.Min(c.G, c.B));
                    depth[i, j] = value;
                    if (value > max)
                        max = value;
                    if (value < min)
                        min = value;
                }
            }
            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < size; j++)
                {
                    depth[i, j] = (int)((depth[i, j] - min) * (255 / (max - min)));
                }
            }
            return depth;
        }
    }
}
